package com.yazi.mxz.person.controller.shop;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.annotation.Resource;




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.PageLink;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Sort;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.entity.beans.LocalSaleGoods;
import com.yazi.mxz.common.entity.beans.Order;
import com.yazi.mxz.common.entity.beans.Store;
import com.yazi.mxz.common.entity.beans.StoreGoods;
import com.yazi.mxz.common.entity.custom.LocalSales4Sync;
import com.yazi.mxz.common.entity.custom.Order4Search;
import com.yazi.mxz.common.entity.enums.OrderStatus;
import com.yazi.mxz.common.exception.MxzStoreGoodsException;
import com.yazi.mxz.common.service.MemberService;
import com.yazi.mxz.common.service.OrderService;
import com.yazi.mxz.common.service.StoreService;
import com.yazi.mxz.person.controller.MyPageLink;

@Controller("shop-orderController")
@RequestMapping("/shop/order")
public class OrderController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(OrderController.class);
	
	@Resource
	OrderService orderService;
	@Resource
	MemberService memberService;
	@Resource
	StoreService storeService;
	
	@RequestMapping("/list")
	public String list(TimeType timeType, Order4Search order, Searching si, Model model) {
		debug(log, "进入订单列表页面");
		// 结束新订单通知
		Store store = getStore(true);
		store.setIsNewOrder(false);
		storeService.merge(store);
		
		// 查店铺未删除的
		store = new Store();
		store.setStoreId(getStoreId());
		order.setStore(store);
		order.setIsStoreDel(false);
		// 每页10条
		si.setPageSize(10);
		// 默认按时间倒序
		if (null == si.getSorts()) {
			List<Sort> sorts = new ArrayList<Sort>();
			sorts.add(new Sort("orderTime", true));
			si.setSorts(sorts);
		}
		
		if (null != timeType) {
			if (timeType.equals(TimeType.TODAY)) {
				GregorianCalendar cal = new GregorianCalendar();
				order.setEndTime(cal.getTimeInMillis());// 结束时间(当前时间)
				cal.set(Calendar.HOUR_OF_DAY, 0);
				cal.set(Calendar.MINUTE, 0);
				cal.set(Calendar.SECOND, 0);
				cal.set(Calendar.MILLISECOND, 0);
				order.setStartTime(cal.getTimeInMillis());// 开始时间(今天0时)
				
			} else if (timeType.equals(TimeType.WEEK)) {
				GregorianCalendar cal = new GregorianCalendar();
				order.setEndTime(cal.getTimeInMillis());// 结束时间(当前时间)
				cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
				cal.set(Calendar.HOUR_OF_DAY, 23);
				cal.set(Calendar.MINUTE, 59);
				cal.set(Calendar.SECOND, 59);
				cal.set(Calendar.MILLISECOND, 999);
				order.setStartTime(cal.getTimeInMillis());// 开始时间(周一0时)
			}
		}
		Page<Order> page = orderService.list(order, si);
		PageLink pl = new MyPageLink(page.getPaging());
		
		model.addAttribute("list", page.getList());
		model.addAttribute("pl", pl);
		model.addAttribute("timeType", timeType);
		model.addAttribute("order", order);
		model.addAttribute("statuses", OrderStatus.values());
		model.addAttribute("timeTypes", TimeType.values());
		return "shop/order_list";
	}
	
	@RequestMapping("/edit")
	public String edit() {
		return "shop/test_order_edit";
	}
	
	@RequestMapping("/statusDo/json")
	@ResponseBody
	public ObjectResult<?> upStatusDoJson(long orderId, OrderStatus status) {
		debug(log, "更新订单状态");
		ObjectResult<OrderStatus> jsonResult = new ObjectResult<OrderStatus>();
		try {
			status = orderService.editStatusByStore(getStore(true), orderId, status);
			if (null != status) {
				jsonResult.setResult(status);
				jsonResult.setOk();
			} else {
				jsonResult.setFail();
			}
		} catch (Exception e) {
			error(log, e, "更新订单状态异常");
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/delDo/json")
	@ResponseBody
	public StatusResult delDoJson(long orderId) {
		debug(log, "删除订单");
		StatusResult jsonResult = new StatusResult();
		try {
			if(orderService.removeByStore(getStore(true), orderId)) {
				jsonResult.setOk();
			} else {
				jsonResult.setFailMessage("删除失败");
			}
		} catch (Exception e) {
			error(log, e, "删除订单异常");
			jsonResult.setErrorMessage("删除失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/listStatus/json")
	@ResponseBody
	public ObjectResult<?> listStatusJson() {
		debug(log, "获取订单状态枚举列表");
		ObjectResult<OrderStatus[]> jsonResult = new ObjectResult<OrderStatus[]>();
		jsonResult.setResult(OrderStatus.values());
		jsonResult.setOk();
		return jsonResult;
	}
	
	@RequestMapping("/addDo/json")
	@ResponseBody
	public ObjectResult<?> addDoJson(long saleId, ListObject listObj, Float pay, Float change) {
		debug(log, "添加订单(线下销售)");
		ObjectResult<String> jsonResult = new ObjectResult<String>();
		try {
			Order order = orderService.addByStore(getStore(true), getMember(), saleId, listObj.getFsg(), pay, change);
			jsonResult.setResult(order.getOrderCode());
			jsonResult.setOk();
		} catch (MxzStoreGoodsException e) {
			debug(log, "添加订单失败:" + e.getMessage());
			jsonResult.setCode("" + e.getCode().getValue());
			jsonResult.setResult("" + ((StoreGoods)e.getData()).getStoreGoodsId());
			jsonResult.setFailMessage(e.getMessage());
		} catch (MyException e) {
			debug(log, "添加订单失败:" + e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "添加订单异常");
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	
	@RequestMapping("/add4SyncDo/json")
	@ResponseBody
	public StatusResult addSome4SyncDoJson(@RequestBody LocalSales4Sync list) {
		debug(log, "添加离线订单");
		StatusResult jsonResult = new StatusResult();
		try {
			orderService.addByStoreForSync(getStore(true), list);
			jsonResult.setOk();
		} catch (MyException e) {
			jsonResult.setFailMessage(e.getMessage());
		} catch (Exception e) {
			error(log, e, "添加订单异常");
			jsonResult.setErrorMessage("操作失败，请联系管理员");
		}
		return jsonResult;
	}
	
	@RequestMapping("/print/online")
	public String printOnline() {
		debug(log, "线上销售小票打印");
		
		return "shop/order_print_online";
	}
	
	public static enum TimeType {
		TODAY("今天"),
		WEEK("本周");
		
		private String text;

		TimeType(String text) {
			this.text = text;
		}

		public String getText() {
			return this.text;
		}
		
		public int getValue() {
			return this.ordinal();
		}
		
		public String getName2() {
			return this.name();
		}
	}
	
	public static class ListObject {
		List<LocalSaleGoods> fsg;

		public List<LocalSaleGoods> getFsg() {
			return fsg;
		}

		public void setFsg(List<LocalSaleGoods> fsg) {
			this.fsg = fsg;
		}

	}
}
